package com.easylinkin.linkappapi.lobar.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.lobar.dto.UserCertificateDTO;
import com.easylinkin.linkappapi.lobar.entity.UserCertificate;
import com.easylinkin.linkappapi.lobar.entity.WarningConfig;
import com.easylinkin.linkappapi.lobar.mapper.UserCertificateMapper;
import com.easylinkin.linkappapi.lobar.mapper.WarningConfigMapper;
import com.easylinkin.linkappapi.lobar.service.UserCertificateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 资质证书 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
public class UserCertificateServiceImpl extends ServiceImpl<UserCertificateMapper, UserCertificate> implements UserCertificateService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Autowired
  private WarningConfigMapper warningConfigMapper;

  /**
   * 增加
   * @param userCertificate
   * @return UserCertificate
   */
  @Override
  public String insert(UserCertificate userCertificate) {
    /**
     * 验证重复
     */
    //是否用毫秒值替代标识，如果有替代需要返回给前端
    boolean flag = false;
    //当新增时没有userId时用毫秒值替代。
    if(StringUtils.isBlank(userCertificate.getUserId())){
      userCertificate.setUserId(System.currentTimeMillis()+"");
      flag = true;
    }
    this.checkExist(userCertificate);
    //设置基本属性
    this.setBase(userCertificate);
    this.save(userCertificate);
    return flag?userCertificate.getUserId():null;
  }

  /**
   * 根据id编辑
   * @param userCertificate
   */
  @Override
  public void updateOne(UserCertificate userCertificate) {
    /**
     * 验证重复
     */
    this.checkExist(userCertificate);
    //设置基本属性
    this.setBase(userCertificate);
    this.updateById(userCertificate);
  }

  /**
   * @Description: 批量编辑用户id
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void updateByUserId(UserCertificate userCertificate) {
    UpdateWrapper<UserCertificate> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("user_id_",userCertificate.getUserId())
        .set("user_id_",userCertificate.getNewUserId());
    baseMapper.update(null,updateWrapper);
  }

  /**
   * @Description: 根据用户id删除
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void deleteByUserId(UserCertificate userCertificate) {
    QueryWrapper<UserCertificate> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("user_id_",userCertificate.getUserId());
    baseMapper.delete(queryWrapper);
  }

  @Override
  public List<UserCertificateDTO> queryList(UserCertificate userCertificate) {
    List<UserCertificate> userCertificateList = baseMapper.queryList(userCertificate);
    List<UserCertificateDTO> certificateDTOS = BeanUtil
        .copyToList(userCertificateList, UserCertificateDTO.class);
    //判断证书是否过期
    WarningConfig warningConfig;
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    QueryWrapper<WarningConfig> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("tenant_id_",tenantId)
        .or().isNull("tenant_id_");
    List<WarningConfig> warningConfigs = warningConfigMapper
        .selectList(queryWrapper);
    List<WarningConfig> collect = warningConfigs.stream()
        .filter(c -> tenantId.equals(c.getTenantId()))
        .collect(Collectors.toList());
    if (collect.size() >0){
      warningConfig = collect.get(0);
    }else {
      warningConfig = warningConfigs.get(0);
    }
    Integer certificate = warningConfig.getCertificate();
    certificateDTOS.forEach(c -> {
      Date stopTime = c.getStopTime();
      c.setStatus(1);
      if (null != stopTime){
        if (new Date().getTime() >= stopTime.getTime()){
          c.setStatus(3);
        }else {
          long between = DateUtil.between(new Date(), DateUtil.endOfDay(stopTime),DateUnit.DAY);
          if (between>0 && between <=certificate){
            c.setStatus(2);
          }
        }
      }
    });
    return certificateDTOS;
  }

  /**
   * 验证重复
   */
  private void checkExist(UserCertificate userCertificate) {
    QueryWrapper<UserCertificate> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.eq("user_id_",userCertificate.getUserId());
    queryWrapper.eq("name_",userCertificate.getName());
    //编辑的时候存在id
    Optional.ofNullable(userCertificate.getId()).ifPresent(id -> queryWrapper.ne("id_",userCertificate.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该资质证书已存在");
    }
  }

  /**
   * 设置基本属性
   * @param userCertificate
   */
  private void setBase(UserCertificate userCertificate) {
    userCertificate.setModifyTime(new Date());
    userCertificate.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (null == userCertificate.getId()){
      userCertificate.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      userCertificate.setCreateTime(new Date());
    }
  }
}
